package com.wondersgroup.fjzlpt.org.service.impl.jtqy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.quick.framework.boot.repository.nosql.mongodb.inter.IMongoOperator;
import com.quick.framework.boot.repository.sql.bean.SQLBean;
import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.ExcelOrWordUtils;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.IdCardUtils;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.org.dao.inter.fwb.FwbDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.hzgl.FpfwDao;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.*;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdjbxxDao;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdryDao;
import com.wondersgroup.fjzlpt.org.dao.inter.xymb.XymbDAO;
import com.wondersgroup.fjzlpt.org.service.inter.jtqy.JtqyService;
import com.wondersgroup.fjzlpt.org.util.ControllerCommonUtil;

import com.wondersgroup.fjzlpt.org.util.PdfFileUtil;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class JtqyServiceImpl implements JtqyService {
    @Autowired
    private CygxDAO cygxDao;
    @Autowired
    private FwbgxDAO fwbgxDao;
    @Autowired
    private JmrqflgxDAO jmrqflgxDao;
    @Autowired
    private JmxxDAO jmxxDao;
    @Autowired
    private QyxxDAO qyxxDao;
    @Autowired
    private TdjbxxDao tdjbxxDao;
    @Autowired
    private ZjsqDao zjsqDao;
    @Autowired
    private TdryDao tdryDao;
    @Autowired
    private FwbDAO fwbDao;
    @Autowired
    private FpfwDao fpfwDao;
    @Autowired
    private QysjbDao qysjbDao;
    @Autowired
    private XymbDAO xymbDAO;
    @Autowired
    private IMongoOperator mongoOperator;
    @Autowired
    private YbfwxgxDao ybfwxgxDao;

    private static final String xy_tableName = "JTQYXY"; //家庭签约协议--保存表名

    /**
     * 查询签约信息分页对象
     *
     * @param map
     * @return
     */
    public JSONObject queryPage(Map<String, String> map) {
        //return qyxxDao.queryALLPage(map);
        return qyxxDao.queryPageOnView(map);
    }

    /**
     * 保存签约信息数据
     *
     * @param map
     * @return JSONObject
     */
    @Override
    public JSONObject save(Map<String, String> map) {
        String qyxxId = map.get("QYXXID");
        ResultObject ro = new ResultObject();
        if (StringUtils.isEmpty(qyxxId)
                && StringUtils.isEmpty(map.get("QYXXIDS"))) {// 新增家庭签约数据
            // insert(map, ro);
        } else {// 修改家庭签约数据
            // update(map, ro);
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    /**
     * 删除签约信息数据
     *
     * @param map
     * @return
     */
    public JSONObject delete(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        try {
            qyxxDao.deleteForPrimaryKey(map);//签约信息
            ybfwxgxDao.deleteBatch(map); //医保服务项关系
            fwbgxDao.deleteBatch(map); //服务包关系
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000601","删除签约记录失败!");
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    /**
     * 初始化签约信息数据
     *
     * @param map
     * @return
     */
    @Override
    public JSONObject initQyxxData(Map<String, String> map) {
        JSONObject jtqy = new JSONObject();
        // 查询居民信息
        Map jmxxQryMap = new HashMap();// 居民基本信息查询条件
        Map jmrqflQryMap = new HashMap();// 居民人群分类查询条件

        Map qyxxQryMap = new HashMap();// 签约信息查询条件
        Map cygxQryMap = new HashMap();// 家庭成员关系信息查询条件

        Map fwbQryMap = new HashMap();// 服务包查询条件

        String value = map.get("JMXXID");
        if (!StringUtils.isEmpty(value)) {
            jmxxQryMap.put("JMXXID", value);
            qyxxQryMap.put("JMXXID", value);
            jmrqflQryMap.put("JMXXID", value);
        }
        value = map.get("ZJHM");
        if (!StringUtils.isEmpty(value)) {
            jmxxQryMap.put("ZJHM", value);
        }
        value = map.get("QYXXID");
        if (!StringUtils.isEmpty(value)) {
            qyxxQryMap.put("QYXXID", value);
            fwbQryMap.put("QYXXID", value);
        }
        if (jmxxQryMap.size() > 0) {// 居民信息
            JSONObject jmxx = jmxxDao.queryOne(jmxxQryMap);
            if (jmxx != null
                    && !StringUtils.isEmpty((String) jmxx.get("JMXXID"))) {
                jmrqflQryMap.put("JMXXID", jmxx.get("JMXXID"));
                cygxQryMap.put("JMXXID", jmxx.get("JMXXID"));
                jtqy.put("JMXX", jmxx);
            }
        }
        if (jmrqflQryMap.size() > 0) {// 居民人群分类信息
            JSONArray rqflgxArr = jmrqflgxDao.queryList(jmrqflQryMap);
            if (rqflgxArr != null && rqflgxArr.size() > 0) {
                jtqy.put("RQFL", rqflgxArr);
            }
        }
        if (cygxQryMap.size() > 0) {// 成员关系
            JSONArray jtcyArr = cygxDao.queryList(cygxQryMap);//
            if (jtcyArr != null && jtcyArr.size() > 0) {
                Iterator<Object> it = jtcyArr.iterator();
                JSONObject ob = null;
                Map paramMap = null;
                JSONObject jtcyObj = null;
                while (it.hasNext()) {//
                    ob = (JSONObject) it.next();
                    String sfzh = (String) ob.get("SFZH");
                    paramMap = new HashMap();
                    paramMap.put("SFZH", sfzh);
                    jtcyObj = jmxxDao.queryOne(paramMap);
                    if (jtcyObj != null
                            && !StringUtils.isEmpty((String) jtcyObj
                            .get("JMXXID"))) {// 家庭成员Obj
                        paramMap.clear();
                        paramMap.put("JMXXID", jtcyObj.get("JMXXID"));
                        JSONObject fwbObj = fwbgxDao.queryOne(paramMap);// 查询服务包对象
                        if (fwbObj != null) {// 服务包Obj
                            ob.put("FWBMC", fwbObj.get("FWBMC"));
                            ob.put("FWBID", fwbObj.get("FWBID"));
                        }
                    }
                }
                jtqy.put("JTCY", jtcyArr);
            }
        }

        if (qyxxQryMap.size() > 0) {// 签约信息
            JSONObject jsonQyxx = qyxxDao.queryOne(qyxxQryMap);
            if (jsonQyxx != null) {
                jtqy.put("QYXX", jsonQyxx);
            }
        }
        if (fwbQryMap.size() > 0) {// 查询服务包
            JSONArray fwbArray = fwbgxDao.queryList(fwbQryMap);
            if (fwbArray != null && fwbArray.size() > 0) {
                jtqy.put("FWB", fwbArray);
            }
        }
        return jtqy;
    }

    /**
     * 查询导出数据列表
     *
     * @param map
     * @return
     */
    public JSONArray queryExportList(Map<String, String> map) {
        JSONArray jsary = new JSONArray();
        try {
            map.put("QYLX", "01");
            jsary = qyxxDao.queryAllOnView(map);
            JSONObject qyztObj = JSONObject.parseObject("{'00':'预签约','01':'已签约','02':'转介中','03':'已解约','04':'已到期'}");
            for (int i = 0; i < jsary.size(); i++) {
                JSONObject item = jsary.getJSONObject(i);
                item.put("QYZT", qyztObj.get(item.get("QYLX")));
            }
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000602","查询签约数据失败！");
        }
        return jsary;
    }

    /**
     * 查询正常可用的团队
     *
     * @param map
     * @return
     */
    @Override
    public JSONObject queryNormalTdxx(Map<String, String> map) {
        JSONObject result = new JSONObject();
        try {
            JSONArray zjtdArr = tdjbxxDao.queryTdxxByUserInfo(map);
            result.put("data", zjtdArr);
            result.put("state", "true");
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000603","查询转介团队失败，请稍后重试！");
        }
        return result;
    }

    @Override
    public JSONObject saveZjxx(Map<String, String> map) {
        ResultObject ro = new ResultObject();

        String XQYTD = map.get("ZJTDID");// 现签约团队
        String XQYYS = map.get("XQYYS"); //现签约医生
        String ZJYY = map.get("ZJYY");// 转介原因
        String YQYTD = map.get("YQYTD");// 原签约团队
        String qyxxids = map.get("QYXXIDS");// 签约信息ID数组
        String fwbids = map.remove("FWBIDS");// 签约信息FWB数组
        String userid = map.remove("USERID");// 签约信息FWB数组
        String[] qyxxidAry = qyxxids.split(",");
        String[] fwbidAry = fwbids.split(";");

        List<Map> zjryList = new ArrayList<Map>();// 转介申请批量插入的map
        List<Object[]> list = new ArrayList<>();
        for (int i = 0; i < qyxxidAry.length; i++) {
            String[] fwbid = fwbidAry[i].split(",");
            Map<String, Object> zjsqMap = new HashMap<>();// 转介申请批量插入的map
            String ZJSQID = UUID.randomUUID().toString();
            zjsqMap.put("ZJSQID", ZJSQID);
            zjsqMap.put("QYXXID", qyxxidAry[i]);
            zjsqMap.put("SQRQ", new Date());
            zjsqMap.put("SHZT", "0");
            zjsqMap.put("ZJYY", ZJYY);
            zjsqMap.put("XQYTD", XQYTD);
            zjsqMap.put("XQYYS",XQYYS);
            zjsqMap.put("YQYTD", YQYTD);
            zjsqMap.put("USERID", userid);
            zjryList.add(zjsqMap);
            for (String id : fwbid) {
                List<Object> paramsList = new ArrayList<>();
                paramsList.add(ZJSQID);
                paramsList.add(id);
                list.add(paramsList.toArray(new Object[paramsList.size()]));
            }
        }

        try {
            map.put("QYZT", "02");
            qyxxDao.updateByCondition(map);
            zjsqDao.zjsqFwbAdd(list);
            zjsqDao.insertBatch(zjryList);
            ro.setInfo("success", "转介申请成功，请等待转入团队审核。您可以在签约查询中查看审核结果！");
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000604","转介申请失败，请稍后再试！");
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    /**
     * 分页查询待审核的转介申请
     *
     * @param map
     * @return
     */
    @Override
    public JSONObject queryZjsqByPage(Map<String, String> map) {
        return zjsqDao.queryPage(map);
    }

    /**
     * 批量审核转介申请
     *
     * @param map
     * @return
     */
    @Override
    public JSONObject checkZjsq(Map<String, String> map) {
        ResultObject ro = new ResultObject();

        String SHZT = map.get("SHZT");
        String USERID = map.get("USERID"); //当前登录用户ID
        String zjryStr = map.get("zjryArr");

        try {
            JSONArray zjryArr = JSONArray.parseArray(zjryStr);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < zjryArr.size(); i++) {
                Map<String, Object> item = (Map) zjryArr.getJSONObject(i);
                item.remove("SQRQ");//避免非Date导致更新失败
                item.put("SHZT", SHZT);
                item.put("SHYH", USERID);
                item.put("SHRQ", new Date());
                zjsqDao.updateForPrimaryKey(item);

                /**
                 * 1.审核通过则医疗团队要改为转介团队，而QYLX不管如何都要改为“已签约”
                 * 2.原团队已分配未完成的任务改为"作废":FWZT=2
                 * 3.审核通过时，qyxx表中的"操作人员ID"要改为当前用户：处理批量续约时操作人员不对的bug
                 */
                item.put("QYLX", "01"); //1
                if ("1".equals(SHZT)) {
                    item.put("YLTDID", item.get("XQYTD"));
                    fpfwDao.freezeYfprw(item.get("QYXXID").toString()); //2
                    item.put("USID",item.get("XQYYS"));//3   XQYYS==现签约医生

                    //保存协议及其相关表操作
                    item.put("SJLX","03"); //事件类型
                    item.put("BZ","转介服务");
                    item.put("YLJGMC",map.get("YLJGMC"));
                    item.put("PTJGID",map.get("PTJGID"));
                    item.put("SJGLID",item.get("ZJSQID")); //时间关联id==转介申请id
                    item.put("CONTENT",map.get("CONTENT"));//批量时item中应该有自己的CONTENT
                    item.put("XYH",map.get("XYH")); //批量时item中应该有自己的XYH
                    item.put("YSID",USERID);
                    item.put("YSXM",map.get("XM"));
                    item.put("TDID",item.get("XQYTD"));
                    item.put("TDMC",item.get("XQYTDMC"));
                    this.addXyToMongoDbAndRecord(item, ro);
                }

                item.remove("JYSJ");
                item.remove("JSSJ");
                item.remove("QYSJ");
                item.remove("SXSJ");

                qyxxDao.updateForPrimaryKey(item);

            }
            ro.setInfo("success", "处理成功");

        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            String errMsg = "处理失败，请稍后再试!";
            if(!ro.isState()){
                errMsg = (String)ro.getInfo("faultInfo");
            }else{
                ro.changeFaultState(errMsg);
            }
            throw new ServiceException("ERR-000605",errMsg);
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    @Override
    public JSONObject jyfw(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        try {
            String qyxxId = map.get("QYXXIDS");
            String[] jmxxidArr = map.get("JMXXIDS").split(",");
            String[] qyxxidArr = qyxxId.split(",");
            SQLBean sqlBean = new SQLBean();

            //mySql数据库
			/*StringBuffer sb = new StringBuffer(" update tb_jtqy_qyxx c inner join ( \n");
			sb.append(" select a.qyxxid from tb_jtqy_qyxx a left join tb_jtqy_qyxx b  \n");
			sb.append(" on a.jmxxid = b.jmxxid  WHERE A.qylx = '05' \n");
			sb.append(" AND b.QYxxid in (  ");
			for (String id : ids) {
				Map sqlMap = new HashMap<>();
				sqlMap.put("QYXXID", id);
				sb.append(" '" + id + "' ,");
				sqlMap.put("QYLX", "03");
				sqlMap.put("JYSJ",new Date());
				sqlMap.put("ZTMS", map.get("ZTMS"));
				sqlMap.put("JYYH", map.get("JYYH"));
				qyxxDao.updateForPrimaryKey(sqlMap);
			}
			sb.replace(sb.length() - 1, sb.length(), " ) \n");
			sb.append(" ) d set c.sfyx = '1' where c.qyxxid = d.qyxxid ");*/

            //oracle数据库
            StringBuffer sb = new StringBuffer("update tb_jtqy_qyxx c set c.sfyx = '1' where c.qyxxid in (\n");
            sb.append("select a.qyxxid from tb_jtqy_qyxx a left join tb_jtqy_qyxx b  \n");
            sb.append("on a.jmxxid = b.jmxxid  WHERE A.qylx = '05' \n");
            sb.append("AND b.QYxxid in (");
            for (int i=0;i<qyxxidArr.length;i++) {
                Map sqlMap = new HashMap<>();
                sqlMap.put("QYXXID", qyxxidArr[i]);
                sb.append(" '" + qyxxidArr[i] + "' ,");
                sqlMap.put("QYLX", "03");
                sqlMap.put("JYSJ", new Date());
                sqlMap.put("ZTMS", map.get("ZTMS"));
                sqlMap.put("JYYH", map.get("JYYH"));
                qyxxDao.updateForPrimaryKey(sqlMap);

                //保存协议及其相关表操作
                map.put("JMXXID",jmxxidArr[i]);
                map.put("QYXXID",qyxxidArr[i]);
                map.put("SJLX","05"); //事件类型
                map.put("BZ","解约服务");

                map.put("YSID",map.get("JYYH"));
                map.put("YSXM",map.get("XM"));
                this.addXyToMongoDbAndRecord(map, ro);
            }
            sb.replace(sb.length() - 1, sb.length(), " ) \n");
            sb.append(" ) ");

            sqlBean.setSql(sb.toString());
            qyxxDao.execute(sqlBean);


            return (JSONObject) JSON.toJSON(ro);
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            String errMsg = "解约申请出错啦！请稍后再试";
            if(!ro.isState()){
                errMsg = (String)ro.getInfo("faultInfo");
            }else{
                ro.changeFaultState(errMsg);
            }
            throw new ServiceException("ERR-000606",errMsg);
        }
    }

    @Override
    public JSONObject bgfwb(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        try {
            JSONArray bgidArr = qyxxDao.updateFwbbg(map);
            //保存协议及其相关表操作
            JSONArray JMXXIDS = JSONArray.parseArray(map.get("JMXXIDS"));
            JSONArray QYXXIDS = JSONArray.parseArray(map.get("QYXXIDS"));
            JSONArray TDIDS = JSONArray.parseArray(map.get("TDIDS"));
            JSONArray TDMCS = JSONArray.parseArray(map.get("TDMCS"));

            Map base = new HashMap();
            base.put("SJLX","04"); //事件类型
            base.put("BZ","变更服务包");
            base.put("YSID",map.get("YSID"));
            base.put("YSXM",map.get("YSXM"));
            base.put("PTJGID",map.get("PTJGID"));
            base.put("YLJGMC",map.get("YLJGMC"));
            base.put("CONTENT",map.get("CONTENT"));
            base.put("XYH",map.get("XYH"));

            for(int i=0;i<JMXXIDS.size();i++){
                Map item = new HashMap();
                item.putAll(base);
                item.put("JMXXID",JMXXIDS.getString(i));
                item.put("QYXXID",QYXXIDS.getString(i));
                item.put("SJGLID",bgidArr.getString(i)); //时间关联id==变更id
                item.put("TDID",TDIDS.getString(i));
                item.put("TDMC",TDMCS.getString(i));
                this.addXyToMongoDbAndRecord(item, ro);

                //变更医保服务项
                ybfwxgxDao.deleteBatch(item);
                item.put("YBFWX_ARR",map.get("YBFWX_ARR"));
                ybfwxgxDao.insertBatch(item);
            }
            return (JSONObject) JSON.toJSON(ro);
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            String errMsg = "变更服务包申请出错啦！请稍后再试。";
            if(!ro.isState()){
                errMsg = (String)ro.getInfo("faultInfo");
            }else{
                ro.changeFaultState(errMsg);
            }
            throw new ServiceException("ERR-000607",errMsg);
        }
    }

    /**
     * 查询新增签约初始化数据
     */
    public JSONObject queryManagerInitData(Map<String, String> map) {
        JSONObject json = new JSONObject(2);
        JSONArray fwbArray = fwbDao.queryAll(map);// 服务包查询条件
        JSONArray tdArray = tdjbxxDao.queryTdxxByUserInfo(map);// 团队基本信息
        json.put("FWBXX", fwbArray);
        json.put("TDXX", tdArray);
        return json;
    }

    @Override
    public JSONObject findQyxxById(Map<String, String> map) {
        JSONObject initData = queryManagerInitData(map);
        JSONObject jmxx = jmxxDao.queryOne(map);// 居民基本信息查询条件
        if (!jmxx.isEmpty()) {
            map.put("JMXXID", jmxx.getString("JMXXID"));
            JSONArray rqflgxArr = jmrqflgxDao.queryRqflByJMXXID(jmxx.getString("JMXXID"));// 居民人群分类查询条件
            JSONArray jtcyArr = cygxDao.queryList(map);// 家庭成员关系信息查询条件
            initData.put("RQFL", rqflgxArr);
            initData.put("JTCY", jtcyArr);
        }
        jmxx.put("ZJHM", map.get("ZJHM"));
        initData.put("JMXX", jmxx);
        return initData;
    }

    @Override
    public JSONObject addQy(Map map) {
        ResultObject ro = new ResultObject();
        try {
            JSONObject JMXX = JSON.parseObject(map.get("JMXX").toString());
            JMXX.put("JGXZQHDM" , map.get("JGXZQHDM"));
            //再次验证是否已经签约
            JSONObject existObj = this.isExist((Map)JMXX);
            if (!existObj.getBoolean("state")) {
                return existObj;
            }
            JMXX.put("CSRQ", FormatDate.getDateY_M_D(JMXX.get("CSRQ").toString()));

            String jmxxId = JMXX.getString("JMXXID");
            if (!StringUtils.isEmpty(jmxxId)) {
                jmxxDao.updateForPrimaryKey(JMXX);// 修改个人基本信息
            } else {
                jmxxId = UUID.randomUUID().toString();
                JMXX.put("JMXXID", jmxxId);
                jmxxDao.insert(JMXX);// 新增个人基本信息
            }
			/*人群分类*/
            jmrqflgxDao.deleteRqflgxByJmxxId(jmxxId);
            List<Map> list = new ArrayList<>();
            String RQFL = map.get("RQFL").toString();
            if (!StringUtils.isEmpty(RQFL)) {
                String[] rqflid = RQFL.split(",");
                for (String id : rqflid) {
                    Map<String, String> rqflMap = new HashMap<>();
                    rqflMap.put("RQFLID", id);
                    rqflMap.put("JMXXID", jmxxId);
                    list.add(rqflMap);
                }
            }
            jmrqflgxDao.insertBatch(list);
			/*家庭成员*/
            cygxDao.deleteByJmxxId(jmxxId);// 删除家庭成员
            JSONArray JTCY = JSON.parseArray(map.get("JTCY").toString());
            if (JTCY != null && !JTCY.isEmpty()) {
                Iterator iter = JTCY.iterator();
                while (iter.hasNext()) {
                    JSONObject json = (JSONObject) iter.next();
                    json.put("JMXXID", jmxxId);
                    if (StringUtils.isEmpty(json.getString("RYSX"))) {
                        json.put("RYSX", "1");
                    }
                }
                cygxDao.insertBatch(JTCY.toJavaList(Map.class));
            }
			/*签约信息*/
            JSONObject QYXX = JSON.parseObject(map.get("QYXX").toString());
            QYXX.put("QYSJ", FormatDate.getDate("yyyy-MM-dd HH:mm:ss", QYXX.getString("QYSJ")));
            QYXX.put("SXSJ", FormatDate.getDateY_M_D(QYXX.getString("SXSJ")));
            QYXX.put("JSSJ", FormatDate.getDateY_M_D(QYXX.getString("JSSJ")));
            //QYXX.put("JYSJ", FormatDate.getDateY_M_D(QYXX.getString("JYSJ")));

			/*签约信息ID*/
            String qyxxid = UUID.randomUUID().toString();
            QYXX.put("QYXXID", qyxxid);
            QYXX.put("JMXXID", jmxxId);
            QYXX.put("YLJGID", map.get("YLJGID").toString());
            QYXX.put("USID", map.get("USID").toString());
            Object QYLX = map.get("QYLX");
            if (QYLX == null) {
                QYXX.put("QYLX", "01");
            } else {
                QYXX.put("QYLX", QYLX);
            }
            QYXX.put("SFXY", "0");
            QYXX.put("SFYX", "0");
            qyxxDao.insert(QYXX);// 保存签约信息

			/*服务包信息*/
            String QYFWBXX = map.get("QYFWBXX").toString();
            String QYFWBSX = map.get("QYFWBSX").toString();
            String[] fwbArray = QYFWBXX.split(",");
            String[] fwbsxAry = QYFWBSX.split(",");
            List<Map> fwbMapList = new ArrayList();
            Map paramMap = null;
            for (int i = 0; i < fwbArray.length; i++) {
                paramMap = new HashMap<>();
                // paramMap.put("JMXXID", jmxxId);
                paramMap.put("FWBID", fwbArray[i]);
                paramMap.put("QYXXID", qyxxid);
                paramMap.put("FWBSX", fwbsxAry[i]);
                fwbMapList.add(paramMap);
            }
            fwbgxDao.insertBatch(fwbMapList);// 批量保存服务包关系成员关系
            //int sdf = 1/0;


            //保存协议及其相关表操作
            map.put("JMXXID",jmxxId);
            map.put("QYXXID",qyxxid);
            map.put("SJLX","01"); //事件类型
            map.put("BZ","新增签约");
            map.put("TDID",QYXX.getString("YLTDID"));
            this.addXyToMongoDbAndRecord(map, ro);
            //医保服务项
            ybfwxgxDao.insertBatch(map);
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            String errMsg = "新增家庭签约失败!";
            if(!ro.isState()){
                errMsg = (String)ro.getInfo("faultInfo");
            }else{
                ro.changeFaultState(errMsg);
            }
            throw new ServiceException("ERR-000608",errMsg);
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    @Override
    public JSONObject isExist(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        String ZJHM = map.get("ZJHM");
        String zjhm = IdCardUtils.get18IcOr15Ic(ZJHM);
        if(!StringUtils.isEmpty(zjhm)){
            map.put("ZJHM" , ZJHM + "," + zjhm);
        }
        JSONObject yqyObj = qyxxDao.isExistYqy(map);
        if (qyxxDao.isExist(map)) {
            //ro.changeFaultState("该人员已签约！");

            /*根据 ZJHM + QYLX 查询签约记录*/
            map.put("QYLX","01,02");
            //map.put("NZJHM" , map.get("ZJHM"));
            //map.put("ZJHM" , ZJHM);
            JSONArray qyxxArr = qyxxDao.queryAllOnView(map);
            if(qyxxArr.size()>0){
                JSONObject item = qyxxArr.getJSONObject(0);
                if(!map.get("JGXZQHDM").equals(item.getString("XZQHDM"))){
                    StringBuffer tipBuf = new StringBuffer();
                    tipBuf.append("该居民已在<span style='color:red'>")
                            .append(item.getString("XZQHMC")) //xx区
                            .append(item.getString("YLJGMC")) //xx机构
                            .append("</span>签约，暂不允许进行跨区签约！");
                    ro.changeFaultState(tipBuf.toString());
                }
            }
        }else if (!yqyObj.isEmpty()) {
            ro.setInfo("QYXXID", yqyObj.getString("QYXXID"));
            ro.changeFaultState("该人员已预签约,是否删除预签约记录？");
        }
        map.put("ZJHM" , ZJHM);
        return (JSONObject) JSON.toJSON(ro);
    }

    @Override
    public JSONObject cygxQuery(Map<String, String> map) {
        // TODO Auto-generated method stub
        JSONObject cyxx = new JSONObject();
        JSONArray jtcyArr = cygxDao.queryList(map);// 家庭成员关系信息查询条件
        cyxx.put("JTCY", jtcyArr);
        return cyxx;// 家庭成员关系信息查询条件;
    }

    @Override
    public JSONObject jtcyQyxxQuery(Map<String, String> map) {
        // TODO Auto-generated method stub
        JSONObject jo = qyxxDao.jtcyQyxxQuery(map);
        return jo;
    }

    @Override
    public JSONObject initXyinfomaion(Map<String, String> map) {
        JSONObject jtqyxx = new JSONObject();
        map.put("FWBZT", "1");
        JSONArray fwbArray = fwbDao.queryAll(map);// 服务包查询条件
        JSONArray tdryArray = tdryDao.queryTdcylbAll(map);
        JSONArray jtcyArr = cygxDao.queryList(map);// 家庭成员关系信息查询条件
        jtqyxx.put("JTCY", jtcyArr);
        jtqyxx.put("FWBXX", fwbArray);
        jtqyxx.put("TDRY", tdryArray);
        return jtqyxx;
    }

    @Override
    public JSONObject xyfw(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        try {
            // 修改个人基本信息
            JSONObject JMXX = JSON.parseObject(map.get("JMXX"));

            String CSRQ = JMXX.getString("CSRQ");
            if (!StringUtils.isEmpty(CSRQ)) {
                JMXX.put("CSRQ", new SimpleDateFormat("yyyy-MM-dd").parse(CSRQ));
            }

            String jmxxId = JMXX.getString("JMXXID");
            jmxxDao.updateForPrimaryKey(JMXX);
            //把原签约信息记录改成已续约状态，以防再次续约
            Map<String, String> oldQyxxMap = new HashMap<>();
            oldQyxxMap.put("SFXY", "1");
            oldQyxxMap.put("QYXXID", map.remove("QYXXID"));
            qyxxDao.updateForPrimaryKey(oldQyxxMap);
            // 删除人群分类信息
            jmrqflgxDao.deleteRqflgxByCondition(JMXX);
            if (!StringUtils.isEmpty(map.get("RQFL"))) {
                // 新增人群分类信息
                String rqflxx = map.get("RQFL");
                String[] rqflid = rqflxx.split(",");
                List<Map> list = new ArrayList<>();
                for (String id : rqflid) {
                    Map<String, String> rqflMap = new HashMap<>();
                    rqflMap.put("RQFLID", id);
                    rqflMap.put("JMXXID", jmxxId);
                    list.add(rqflMap);
                }
                jmrqflgxDao.insertBatch(list);
            }

            cygxDao.deleteByJmxxId(jmxxId);// 删除家庭成员
            JSONArray JTCY = JSON.parseArray(map.get("JTCY"));
            if (JTCY != null && !JTCY.isEmpty()) {
                //新增家庭成员
                Iterator iter = JTCY.iterator();
                while (iter.hasNext()) {
                    JSONObject json = (JSONObject) iter.next();
                    json.put("JMXXID", jmxxId);
                    if (StringUtils.isEmpty(json.getString("RYSX"))) {
                        json.put("RYSX", "1");
                    }
                }
                cygxDao.insertBatch(JTCY.toJavaList(Map.class));
            }
            String qyxxid = UUID.randomUUID().toString();//签约信息ID
			/*批量新增服务包信息*/
            String QYFWBXX = map.get("QYFWBXX");
            String QYFWBSX = map.get("QYFWBSX");
            String[] fwbArray = QYFWBXX.split(",");
            String[] fwbsxAry = QYFWBSX.split(",");
            List<Map> fwbMapList = new ArrayList();
            Map paramMap = null;
            for (int i = 0; i < fwbArray.length; i++) {
                paramMap = new HashMap<>();
                paramMap.put("FWBID", fwbArray[i]);
                paramMap.put("QYXXID", qyxxid);
                paramMap.put("FWBSX", fwbsxAry[i]);
                fwbMapList.add(paramMap);
            }
            fwbgxDao.insertBatch(fwbMapList);
            // 保存签约信息
            JSONObject QYXX = JSON.parseObject(map.get("QYXX"));
            QYXX.put("QYXXID", qyxxid);
            QYXX.put("JMXXID", jmxxId);
            QYXX.put("QYLX", "05");
            QYXX.put("SFXY", "0");
            QYXX.put("SFYX", "0");

            //QYSJ,SXSJ,JSSJ,JYSJ
            QYXX.put("QYSJ", FormatDate.getDate("yyyy-MM-dd HH:mm:ss",QYXX.getString("QYSJ")));
            QYXX.put("SXSJ", FormatDate.getDateY_M_D(QYXX.getString("SXSJ")));
            QYXX.put("JSSJ", FormatDate.getDateY_M_D(QYXX.getString("JSSJ")));
            qyxxDao.insert(QYXX);

            //保存协议及其相关表操作
            map.put("JMXXID",jmxxId);
            map.put("QYXXID",qyxxid);
            map.put("SJLX","02"); //事件类型
            map.put("BZ","续约");
            map.put("TDID", QYXX.getString("YLTDID"));
//            map.put("YSID", QYXX.getString("USID"));
//            map.put("YSXM", QYXX.getString("YSXM"));

            this.addXyToMongoDbAndRecord(map, ro);
            //医保服务项
            ybfwxgxDao.insertBatch(map);
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            String errMsg = "续约失败！";
            if(!ro.isState()){
                errMsg = (String)ro.getInfo("faultInfo");
            }else{
                ro.changeFaultState(errMsg);
            }
            throw new ServiceException("ERR-000609",errMsg);
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    @Override
    public JSONObject plxyfw(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        try {
            String[] fwbids = map.get("FWBIDS").split("\\|");// 服务包ID
            String[] fwbsxs = map.get("FWBSX").split("\\|");// 服务包属性
            String userid = map.get("USERID");// 用户ID
            String tdid = map.get("TDID");// 医疗团队ID
            String yljgid = map.get("YLJGID");// 医疗机构ID
            String[] jmxxids = map.get("JMXXIDS").split(",");// 居民信息ID
            String[] xysjAry = map.get("XYSJARY").split("\\|");// 签约时间
            String[] qyxxAry = map.get("QYXXIDS").split(",");// 签约时间
            SQLBean sqlb = new SQLBean(
                    "update TB_JTQY_QYXX SET SFXY = '1' where QYXXID = ? ");
            List<Object[]> list = new ArrayList<>();
            for (String qyxx : qyxxAry) {
                list.add(new Object[]{qyxx});
            }
            sqlb.setBatch(true);
            sqlb.setParamAry(list);
            qyxxDao.execute(sqlb);
            List<Map> fwbMapList = new ArrayList();
            List<Map> qyxxList = new ArrayList();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < jmxxids.length; i++) {
                Map<String, Object> qyMap = new HashMap<String, Object>();
                String jmxxid = jmxxids[i];// 居民信息ID
                String qyxxid = UUID.randomUUID().toString();// 签约信息ID
                String[] fwbxxString = fwbids[i].split(",");
                String[] fwbsx = fwbsxs[i].split(",");
                for (int j = 0; j < fwbxxString.length; j++) {
                    Map<String, String> fwbMap = new HashMap<String, String>();
                    fwbMap.put("FWBID", fwbxxString[j]);
                    fwbMap.put("QYXXID", qyxxid);
                    fwbMap.put("FWBSX", fwbsx[j]);
                    fwbMapList.add(fwbMap);
                }
                String[] xysj = xysjAry[i].split(",");
                qyMap.put("QYXXID", qyxxid);
                qyMap.put("JMXXID", jmxxid);
                qyMap.put("YLTDID", tdid);
                qyMap.put("YLJGID", yljgid);
                qyMap.put("QYSJ", new Date());
                qyMap.put("SXSJ", sdf.parse(xysj[0]));
                qyMap.put("JSSJ", sdf.parse(xysj[1]));
                qyMap.put("USID", userid);
                qyMap.put("QYLX", "05");
                qyMap.put("SFXY", "0");
                qyMap.put("SFYX", "0");
                qyxxList.add(qyMap);
            }
            fwbgxDao.insertBatch(fwbMapList);// 批量保存服务包关系成员关系
            qyxxDao.insertBatch(qyxxList);// 保存签约信息
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000610","批量续约失败！");
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    @Override
    public JSONArray findTdByUserId(Map<String, String> map) {
        // TODO Auto-generated method stub
        return tdjbxxDao.queryTdxxByUserInfo(map);
    }

    @Override
    public JSONArray queryTdxxAll(Map<String, String> map) {
        // TODO Auto-generated method stub
        if (StringUtils.isEmpty(map.get("USERID"))) {
            return tdjbxxDao.queryTdxxByInfo(map);
        } else {
            //map.remove("TDJS");
            return findTdByUserId(map);
        }
    }

    @Override
    public JSONObject findLsjlAll(Map<String, String> map) {
        // TODO Auto-generated method stub
        return qyxxDao.findLsjlAll(map);
    }

    /**
     * 查询一个居民的所有历史签约信息
     *
     * @param map
     * @return
     */
    public JSONObject querySingleUserQyxxAll(Map<String, String> map) {
        return qyxxDao.querySingleUserQyxxAll(map);
    }


    /**
     * 分页查询一个居民历史签约信息到健康城市系统
     *
     * @param map
     * @return
     */
    @Override
    public JSONObject queryQyHistoryByPageToJkcs(Map<String, String> map) {
        return qyxxDao.queryQyHistoryByPageToJkcs(map);
    }

    /**
     * 导出转介审核数据
     *
     * @param map
     * @response
     */
    public void downloadZjsh(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        map.put("XQYTD",map.remove("XQYTD_down"));
        JSONArray dataArr = zjsqDao.queryAll(map);
        //表头
        String titleStr = "{'XM':'姓名','ZJHM':'证件号码','SJHM':'手机号码','JTZZ':'家庭住址','QYSJ':'签约时间','YQYTDMC':'原签约团队','FWBMC':'签约服务包','SQRQ':'申请时间','ZJYYMS':'转介原因','XQYTDMC':'转入团队'}";
        JSONObject title = JSONObject.parseObject(titleStr);
        dataArr.add(0, title);

        //排列循序
        List<String> titleField = new ArrayList<>();
        titleField.add("XM");
        titleField.add("ZJHM");
        titleField.add("SJHM");
        titleField.add("JTZZ");
        titleField.add("QYSJ");
        titleField.add("YQYTDMC");
        titleField.add("FWBMC");
        titleField.add("SQRQ");
        titleField.add("ZJYYMS");
        titleField.add("XQYTDMC");
        ExcelOrWordUtils.downLoadExcelFile(dataArr, titleField, "转介列表", request, response);
    }

    /**
     * 导出签约查询数据
     *
     * @param map
     * @response
     */
    public void downloadQycx(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        JSONArray dataArr = null;

        List<String> titleField = new ArrayList<>();
        String xlsName = null;
        String tableId = map.get("tableId");
        map.put("YLJGID",map.remove("YLJG"));
        if ("allTb".equals(tableId)) {
            xlsName = "全部签约";
            map.put("YLTDID", map.remove("TDID"));
            map.put("SFYX","0");
            dataArr = qyxxDao.queryAllOnView(map);
            JSONObject qyztObj = JSONObject.parseObject("{'00':'预签约','01':'已签约','02':'转介中','03':'已解约','04':'已到期','05':'已续约','06':'拒绝预签约'}");
            for (int i = 0; i < dataArr.size(); i++) {
                JSONObject item = dataArr.getJSONObject(i);
                item.put("QYZT", qyztObj.get(item.get("QYLX")));
            }

            String titleStr = "{'YLJGMC':'所属机构','XM':'姓名','ZJHM':'证件号码','SJHM':'手机号码','JTZZ':'家庭住址','QYSJ':'签约时间','RQFLMC':'人群分类','QYTDMC':'签约团队','FWBMC':'签约服务包','QYZT':'签约状态'}";
            JSONObject title = JSONObject.parseObject(titleStr);
            dataArr.add(0, title);
            titleField.add("YLJGMC");
            titleField.add("XM");
            titleField.add("ZJHM");
            titleField.add("SJHM");
            titleField.add("JTZZ");
            titleField.add("QYSJ");
            titleField.add("RQFLMC");
            titleField.add("QYTDMC");
            titleField.add("FWBMC");
            titleField.add("QYZT");
        } else if ("ydqTb".equals(tableId)) {
            xlsName = "已到期签约";
            map.put("YLTDID", map.remove("TDID"));
            dataArr = qyxxDao.queryAllOnView(map);
            String titleStr = "{'YLJGMC':'所属机构','XM':'姓名','ZJHM':'证件号码','SJHM':'手机号码','JTZZ':'家庭住址','QYSJ':'签约时间','RQFLMC':'人群分类','QYTDMC':'签约团队','FWBMC':'签约服务包','JSSJ':'到期时间'}";
            JSONObject title = JSONObject.parseObject(titleStr);
            dataArr.add(0, title);
            titleField.add("YLJGMC");
            titleField.add("XM");
            titleField.add("ZJHM");
            titleField.add("SJHM");
            titleField.add("JTZZ");
            titleField.add("QYSJ");
            titleField.add("RQFLMC");
            titleField.add("QYTDMC");
            titleField.add("FWBMC");
            titleField.add("JSSJ");
        } else if ("yjyTb".equals(tableId)) {
            xlsName = "已解约居民";
            map.put("YLTDID", map.remove("TDID"));
            dataArr = qyxxDao.queryAllOnView(map);
            String titleStr = "{'YLJGMC':'所属机构','XM':'姓名','ZJHM':'证件号码','SJHM':'手机号码','JTZZ':'家庭住址','QYSJ':'签约时间','RQFLMC':'人群分类','QYTDMC':'签约团队','FWBMC':'签约服务包','JYSJ':'解约时间'}";
            JSONObject title = JSONObject.parseObject(titleStr);
            dataArr.add(0, title);
            titleField.add("YLJGMC");
            titleField.add("XM");
            titleField.add("ZJHM");
            titleField.add("SJHM");
            titleField.add("JTZZ");
            titleField.add("QYSJ");
            titleField.add("RQFLMC");
            titleField.add("QYTDMC");
            titleField.add("FWBMC");
            titleField.add("JYSJ");
        } else {
            xlsName = "已转出居民";
            map.put("YQYTD", map.remove("TDID"));
            String titleStr = "{'YLJGMC':'所属机构','XM':'姓名','ZJHM':'证件号码','SJHM':'手机号码','JTZZ':'家庭住址','QYSJ':'签约时间','RQFLMC':'人群分类','FWBMC':'签约服务包','XQYTDMC':'已转介团队','SQRQ':'转介时间'}";
            JSONObject title = JSONObject.parseObject(titleStr);
            dataArr = zjsqDao.queryAll(map);
            dataArr.add(0, title);
            titleField.add("YLJGMC");
            titleField.add("XM");
            titleField.add("ZJHM");
            titleField.add("SJHM");
            titleField.add("JTZZ");
            titleField.add("QYSJ");
            titleField.add("RQFLMC");
            titleField.add("FWBMC");
            titleField.add("XQYTDMC");
            titleField.add("SQRQ");
        }
        ExcelOrWordUtils.downLoadExcelFile(dataArr, titleField, xlsName, request, response);
    }

    /**
     * 打印协议
     *
     * @param map
     * @param response
     */
//    public void printXy(Map<String, String> map, HttpServletResponse response) {
//        //导出word文件
////        JSONArray list = qyxxDao.queryPrintXyByQyxxids(map);
////        JSONObject pdfObjData = list.getJSONObject(0);
////        ControllerCommonUtil.downLoadWordFile(dataMap, response, "printXy.ftl");
//
//        //导出pdf--模板
////        JSONObject pdfObjData = JSONObject.parseObject(map.get("data"));
////        //pdf文件名称合成：居民姓名+身份证号+医疗机构名称
////        String pdfFileName = pdfObjData.getString("XM") + pdfObjData.getString("ZJHM") + pdfObjData.getString("YFYLJGMC") +".pdf";
////        PdfFileUtil.downLoadPdfFileByModel(response, pdfObjData, map.get("fileModelName"), pdfFileName);
//
//        //导出pdf--html结构
//        //pdf文件名称合成：居民姓名+身份证号+医疗机构名称
//        StringBuffer htmlDocument = new StringBuffer();
//        htmlDocument.append("<body style='font-family:宋体,SimSun,simsun,Microsoft YaHei,楷体,微软雅黑;'>");
//        htmlDocument.append(map.get("htmlDocument"));
//        htmlDocument.append("</body>");
//        String htmlDocStr = htmlDocument.toString().replaceAll("gzbBfh","%");
//        JSONObject pdfObjData = JSONObject.parseObject(map.get("data"));
//        //pdf文件名称合成：居民姓名+身份证号+医疗机构名称
//        String pdfFileName = pdfObjData.getString("XM") + pdfObjData.getString("ZJHM") + pdfObjData.getString("YFYLJGMC") +".pdf";
//        PdfFileUtil.downLoadPdfFileByHtml(response, pdfFileName , htmlDocStr);
//    }

    /**
     * 审核预签约记录（同意签约/拒绝签约）
     *
     * @param map
     * @return
     */
    public JSONObject checkYqyData(Map<String, String> map) {
        JSONObject result = new JSONObject();

        try {
            String type = map.get("type");
            if ("agree".equals(type)) {
                map.put("QYLX", "01");
                result.put("info", "接收签约成功！");
            } else {
                map.put("QYLX", "06");
                map.put("SFYX", "1");
                result.put("info", "拒绝签约成功！");
            }

            String addXy = map.get("addXy");
            if(!StringUtils.isEmpty(addXy)){
                JSONObject sjbData = JSONObject.parseObject(addXy);
                sjbData.put("PTJGID",map.remove("PTJGID"));
                sjbData.put("YLJGMC",map.remove("YLJGMC"));
                sjbData.put("SJLX","01");
                sjbData.put("BZ","新增签约");
                this.addXyToMongoDbAndRecord(sjbData, null);
            }
            qyxxDao.updateForPrimaryKey(map);
            result.put("state", "true");
        } catch (Exception e) {
            result.put("info", "处理失败，请稍后重试！");
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000611","处理失败，请稍后重试！");
        }
        return result;
    }

    /**
     * 保存健康城市系统预签约信息数据
     *
     * @param map
     * @return
     */
    public JSONObject addYqyToJkcs(Map<String, String> map) {

        JSONObject result = new JSONObject();
        try {
            String YLJGID = map.remove("YLJGID");
            JSONObject jmxx = JSONObject.parseObject(map.get("JMXX"));
            map.put("ZJHM",jmxx.getString("ZJHM"));
            if (qyxxDao.isExist(map)) {
                result.put("info", "您已经存在签约记录，不可再次签约！");
            } else if (!qyxxDao.isExistYqy(map).isEmpty()) {
                result.put("info", "您还有一条未审核的预签约记录，不可新增！");
            } else {
                map.put("YLJGID",YLJGID);
                this.saveYqyDataToJkcs(map);
                result.put("info", "预签约成功");
                result.put("state", "true");
            }
        } catch (Exception e) {
            result.put("state", "false");
            result.put("info", "保存预签约数据失败,请稍后重试..");
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000612","保存预签约数据失败");
        }
        return result;
    }

    @Override
    public JSONObject apiQyxxQuery(Map<String, String> map) {
        JSONObject result = new JSONObject(6);
        JSONObject jmxx = jmxxDao.queryOne(map);// 居民基本信息查询条件
        if(jmxx.isEmpty()){
            throw  new ServiceException("ERR-000302","系统中无该患者信息请核对信息后再试！");
        }
        JSONObject yljgxx = qyxxDao.findYljgxxByUserId(map);//机构与人员信息

        /*判断是否跨区签约*/
        Map<String,String> queryQyxxMap = new HashMap<String,String>();
        queryQyxxMap.put("QYLX","01,02");
        queryQyxxMap.put("ZJHM",jmxx.getString("ZJHM"));
        JSONArray qyxxArr = qyxxDao.queryAllOnView(queryQyxxMap);
        if (qyxxArr.size()>0) {
            JSONObject item = qyxxArr.getJSONObject(0);
            if(!item.getString("XZQHDM").equals(yljgxx.getString("JGXZQHDM"))){
                StringBuffer tipBuf = new StringBuffer();
                tipBuf.append("该居民已在")
                        .append(item.getString("XZQHMC")) //xx区
                        .append(item.getString("YLJGMC")) //xx机构
                        .append("签约，暂不允许进行跨区签约！");
                throw new ServiceException("ERR-000301",tipBuf.toString());
            }
        }

        map.put("JGXZQHDM",yljgxx.getString("JGXZQHDM"));
        JSONArray fwbxx = fwbDao.queryAll(map);//服务包信息
        JSONArray tdxx = tdjbxxDao.queryTdxxByUserInfo(map); // 团队信息
        JSONArray rqflgxArr = jmrqflgxDao.queryRqflByJMXXID(map.get("JMXXID"));// 居民人群分类查询条件
        JSONArray jtcyArr = cygxDao.queryList(map);// 家庭成员关系信息查询条件
        result.put("JGRYXX", yljgxx);
        result.put("FWBXX" , fwbxx);
        result.put("TDXX" , tdxx);
        result.put("JMXX" , jmxx);
        result.put("RQFLGX" , rqflgxArr);
        result.put("JTCYGX" , jtcyArr);
        result.put("JGXZQHDM" , yljgxx.getString("JGXZQHDM"));
        result.put("JGXZQHMC" , yljgxx.getString("JGXZQHMC"));
        return result;
    }

    /**
     * "健康城市"预签约数据入库
     *
     * @param map
     * @return
     */
    private JSONObject saveYqyDataToJkcs(Map map) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ResultObject ro = new ResultObject();
        try {
            JSONObject JMXX = JSON.parseObject(map.get("JMXX").toString());
            String CSRQ = JMXX.getString("CSRQ");
            if (!StringUtils.isEmpty(CSRQ)) {
                JMXX.put("CSRQ", sdf.parse(CSRQ));
            }

            //根据身份证号查询该用户在平台是否存在--居民信息
            JSONObject ptJmxx = jmxxDao.queryOne(map); //平台居民信息
            String jmxxId = ptJmxx.getString("JMXXID");
            if (!StringUtils.isEmpty(jmxxId)) {
                JMXX.put("JMXXID", jmxxId);
                jmxxDao.updateForPrimaryKey(JMXX);
            } else {
				jmxxId = UUID.randomUUID().toString();
				JMXX.put("JMXXID", jmxxId);
                //jmxxId = JMXX.getString("JMXXID");
                jmxxDao.insert(JMXX);
            }

            /*人群分类*/
            jmrqflgxDao.deleteRqflgxByJmxxId(jmxxId);
            String RQFL = JMXX.getString("RQFL");
            if (!StringUtils.isEmpty(RQFL)) {
                String[] rqflid = RQFL.split(",");
                List<Map> list = new ArrayList<>();
                for(String id : rqflid){
                    Map<String, String> rqflMap = new HashMap<>();
                    rqflMap.put("RQFLID", id);
                    rqflMap.put("JMXXID", jmxxId);
                    list.add(rqflMap);
                }
                jmrqflgxDao.insertBatch(list);
            }

			/*签约信息*/
            JSONObject QYXX = JSON.parseObject(map.get("QYXX").toString());
            String QYSJ = QYXX.getString("QYSJ");
            if (!StringUtils.isEmpty(QYSJ)) {
                QYXX.put("QYSJ", FormatDate.getDate("yyyy-MM-dd HH:mm:ss", QYSJ));
            }
            String SXSJ = QYXX.getString("SXSJ");
            if (!StringUtils.isEmpty(SXSJ)) {
                QYXX.put("SXSJ", sdf.parse(SXSJ));
            }
            String JSSJ = QYXX.getString("JSSJ");
            if (!StringUtils.isEmpty(JSSJ)) {
                QYXX.put("JSSJ", sdf.parse(JSSJ));
            }
            String JYSJ = QYXX.getString("JYSJ");
            if (!StringUtils.isEmpty(JYSJ)) {
                QYXX.put("JYSJ", sdf.parse(JYSJ));
            }


			/*签约信息ID*/
            String YLJGID = map.get("YLJGID").toString();
            String USID = map.get("USID").toString();
            String qyxxid = UUID.randomUUID().toString();
            QYXX.put("QYXXID", qyxxid);
            QYXX.put("JMXXID", jmxxId);
            QYXX.put("YLJGID", YLJGID);
            QYXX.put("USID", USID);
            QYXX.put("QYLX", "00"); // 00: 预签约
            QYXX.put("SFXY", "0");
            QYXX.put("SFYX", "0");
            qyxxDao.insert(QYXX);// 保存签约信息

			/*服务包信息*/
			String QYFWBXX = map.get("QYFWBXX").toString();
			String QYFWBSX = map.get("QYFWBSX").toString();
			String[] fwbArray = QYFWBXX.split(",");
			String[] fwbsxAry = QYFWBSX.split(",");
			List<Map> fwbMapList = new ArrayList();
			Map paramMap = null;
			for (int i = 0; i < fwbArray.length; i++) {
				paramMap = new HashMap<>();
				// paramMap.put("JMXXID", jmxxId);
				paramMap.put("FWBID", fwbArray[i]);
				paramMap.put("QYXXID", qyxxid);
				paramMap.put("FWBSX", fwbsxAry[i]);
				fwbMapList.add(paramMap);
			}
			fwbgxDao.insertBatch(fwbMapList);// 批量保存服务包关系成员关系
		}catch (Exception e){
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000613","预签约失败！");
		}
		return (JSONObject) JSON.toJSON(ro);
	}


	/**
	 * 通过定时任务修改“签约类型”
	 * @param map
	 * @return JSON对象 { state:1 } || { state:0,info:"xxx" }
	 */
	public JSONObject updateQylxByTimedask(Map map){
	    ResultObject ro = new ResultObject();
		JSONObject result = new JSONObject();
		try {
			JSONArray qyxxidArr = qyxxDao.updateQylxByTimedask(map);
			//添加续约协议
            if(qyxxidArr.size()>0){
                //查询启用中家签协议模板
                Map<String, String> map1 = new HashMap<>();
                map1.put("XYMBLX","01");
                map1.put("ZT","1");
                JSONObject xyObj = xymbDAO.queryOne(map1);
                String XYMBID = xyObj.getString("XYMBID");
                JSONObject jsonObject = mongoOperator.executeQuery("XYMB", QueryBuilder.start("_id").is(new ObjectId(XYMBID)), "CONTENT").getJSONObject(0);

                Document doc = Jsoup.parse(jsonObject.getString("CONTENT"));//通过Jsonp将字符串转为Doc
                Elements jfDiv = doc.select("#jfDiv");//获取id="jfDiv"的元素
                Elements xyhTd = doc.select("#XYH"); //获取协议号的td

                for(int i=0;i<qyxxidArr.size();i++){
                    Map item = qyxxidArr.getJSONObject(i);
                    item.put("FWBIDS",item.get("FWBID").toString().replaceAll(",","|"));
                    //在Div中添加2个属性（data和timeTask)
                    String XYH = qysjbDao.queryMaxXyh(item.get("XZQHDM").toString());
                    jfDiv.attr("data", item.toString()).attr("timeTask","1");
                    xyhTd.html(XYH);
                    item.put("CONTENT",doc.select(".panel").toString());

                    item.put("SJLX","02");
                    item.put("BZ","服务到期，自动续约");
                    this.addXyToMongoDbAndRecord(item,ro);
                }
            }
			result.put("state","1");
		}catch (Exception e){
		    result.put("state","0");
			result.put("info","定时任务执行失败！");
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000614","定时任务执行失败！");
		}
		return result;
	}

	/** 测试jsonp */
    /*public static void main(String[] agrs){
	    JSONObject saveData = new JSONObject();
	    saveData.put("aa","aa");
	    saveData.put("bb","bb");

	    String html = "<div>aa</div><div class='JFDIV'>bb</div><input value='haha' />";
        Document doc = Jsoup.parse(html);
        Elements jfDiv = doc.select(".JFDIV");
        jfDiv.attr("data",saveData.toString());

        System.out.print(jfDiv.toString());
        System.out.print("===============");
        System.out.print(doc.toString());
    }*/



    @Override
    public JSONObject getQyfyxxInfo(String sfzh) {
        JSONObject jo = new JSONObject();
        jo.put("state" , "true");
        JSONArray ary = qyxxDao.getQyfyxxInfo(sfzh);
        if(ary.size() > 0){
            jo.put("qyxx",ary);
        }else{
            jo.put("state" , "false");
            jo.put("faultInfo" , "该人员没有签约信息！");
        }
        return jo;
    }

    /**
     * 保存协议模板到mongo，并且保存记录到表
     * @param map
     * @throws Exception
     */
    @Override
	public void addXyToMongoDbAndRecord(Map map, ResultObject ro) throws Exception {
        String xyContent = map.get("CONTENT").toString().replaceAll("gzbBfh","%")
                .replaceAll("gzbJh","+");

        //查询协议号是否重复
        Document doc = Jsoup.parse(xyContent);
        String xyh = doc.select("#XYH").html(); //获取协议号的td
        Map queryQysj = new HashMap();
        queryQysj.put("XYH", xyh);
        if(StringUtils.isEmpty(xyh)){
            ro.changeFaultState("协议号为空!");
            throw new Exception("协议号为空!");
        }else if(qysjbDao.isExist(queryQysj)){
            ro.changeFaultState("协议号已被使用, 请重新生成!");
            throw new Exception("协议号已被使用, 请重新生成!");
        }

        JSONObject json = new JSONObject();
        json.put("CONTENT", map.get("CONTENT").toString().replaceAll("gzbBfh","%")
                .replaceAll("gzbJh","+"));
        DBObject dbo = (DBObject)com.mongodb.util.JSON.parse(json.toString());
        /*保存协议页面*/
        String XYID = mongoOperator.executeInsertOne(xy_tableName, dbo);
        map.put("XYID",XYID);

        //签约事件表
        if("update".equals(map.get("type"))){
            qysjbDao.updateForPrimaryKey(map);
        }else{
            map.put("ID",UUID.randomUUID().toString());
            map.put("CZSJ",new Date());
            qysjbDao.insert(map);
        }
    }

    /**
     * 分页查询电子协议
     * @param map
     * @return
     */
    public JSONObject queryDzxyByage(Map<String,String> map){
        return qysjbDao.queryPage(map);
    }

    /**
     * 根据协议ID查询协议
     * @param XYID
     * @return
     */
    public JSONObject queryXyByXyid(String XYID){
        JSONObject jsonObject = new JSONObject(1);
        try {
            /*查询mongo存储的模板内容*/
            jsonObject = mongoOperator.executeQuery(xy_tableName, QueryBuilder.start("_id").is(new ObjectId(XYID)), "CONTENT").getJSONObject(0);
            String xyh = qysjbDao.queryXyhByXyid(XYID);
            Document doc = Jsoup.parse(jsonObject.getString("CONTENT"));//通过Jsonp将字符串转为Doc
            doc.select("#XYH").html(xyh);
            jsonObject.put("CONTENT",doc.select(".panel").toString());
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-000901","获取协议出错，请稍后再试！");
        }
        return jsonObject;
    }

    private void update(Map map) throws Exception {
        String XYMBID = (String)map.get("XYMBID");
        JSONObject json = new JSONObject(1);
        String CONTENT = (String)map.remove("CONTENT");
        json.put("CONTENT", CONTENT);
        DBObject dbo = (DBObject)com.mongodb.util.JSON.parse(json.toString());
        /*更新签约协议页面*/
        this.mongoOperator.executeUpdate(this.xy_tableName, QueryBuilder.start("_id").is(new ObjectId(XYMBID)), dbo);
    }

    @Override
    public JSONObject queryQyxyToJkcs(Map<String, String> map) {
        JSONObject result = qysjbDao.queryQyxyId(map);
        //this.queryXyByXyid(result.getString("XYID"));
        return this.queryXyByXyid(result.getString("XYID"));
    }

    /**
     * 根据医生ID查询该医生签约的患者总数
     * @param map {USERID:xxx}
     * @return
     */
    @Override
    public String queryQyzsToJkcs(Map<String,String> map){
        String result = null;

        if(StringUtils.isEmpty(map.get("USERID"))){
            throw new ServiceException("ERR-000902","查询参数有误");
        }else{
            JSONObject qyzsObj = qyxxDao.queryQyzsToJkcs(map);
            result = qyzsObj.getString("QYZS");
        }

        return result;
    }

    @Override
    public JSONObject zsQyxxUpdateForJkcs(Map<String, String> map) {
        ResultObject ro = new ResultObject();
        try {
            map.put("QYLX" , "01");
            qyxxDao.updateForPrimaryKey(map);
            map.put("SJLX" , "01");
            map.put("BZ" , "新增签约");
            this.addXyToMongoDbAndRecord(map, ro);
        }catch (Exception e){
            LoggerUtil.error(e.getMessage());
            String errMsg = "正式签约失败！";
            if(!ro.isState()){
                errMsg = (String)ro.getInfo("faultInfo");
            }else{
                ro.changeFaultState(errMsg);
            }
            throw new ServiceException("ERR-000903", errMsg);
        }
        return (JSONObject) JSON.toJSON(ro);
    }

    /**
     * 查询医保服务项
     * @return
     */
    public JSONArray queryYbfwx(Map<String, String> map){
        return ybfwxgxDao.queryList(map);
    }

    /**
     * 查询协议可选的所有服务包--V_XXWH_FWBXX
     * @return
     */
    public JSONArray queryFwbAllByView(Map<String, String> map){
        return fwbDao.queryAllByView(map);
    }

    /**
     * 查询患者已经签订的所有服务包ID
     * 	--用于前台服务包禁用
     * @return
     */
    @Override
    public JSONObject getYqdFwbid(Map<String, String> map){
        ResultObject ro = new ResultObject();

        try {
            StringBuffer FWBLXS = new StringBuffer();

            JSONArray qyxxArr = qyxxDao.queryQyxxByQysj(map);
            JSONArray syzQyxxArr = qyxxDao.queryQyxxByQysj(map);
            if(qyxxArr.size()>0){
                for(int i=0;i<qyxxArr.size();i++){
                    JSONObject item = qyxxArr.getJSONObject(i);
                    FWBLXS.append(item.getString("FWBLX")+",");
                    if("01".equals(item.getString("QYLX")) || "02".equals(item.getString("QYLX"))){
                        syzQyxxArr.add(item);
                    }
                }
                FWBLXS.deleteCharAt(FWBLXS.length()-1);
            }

            ro.setInfo("FWBLXS_YQD",FWBLXS.toString());//服务包类型_已签订
            ro.setInfo("data",qyxxArr);
        }catch (Exception e){
            LoggerUtil.error(e.getMessage());
            ro.changeFaultState("查询已签订的服务包失败！");
        }
        return (JSONObject) JSON.toJSON(ro);
    }
}
